//
//  RequestManager+HFQ.m
//  AiShangJinFuSalesman
//
//  Created by AiShangTong on 2017/7/10.
//  Copyright © 2018年 AiShangTong. All rights reserved.
//

#import "RequestManager+HFQ.h"



NSString *const HFQErrorDomain = @"com.ASJF.HeFenQi";

@implementation RequestManager (HFQ)


-(NSString*)HFQCurrentTime {
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    long long a=[dat timeIntervalSince1970]*1000;
    NSString *timeString = [NSString stringWithFormat:@"%lld", a];
    return timeString;
}


/**
 数据请求（APP与后台通讯相关）
 
 @param method 请求方式
 @param URLString 请求地址
 @param parameters 参数
 @param success 成功回调
 @param failure 失败回调
 */
-(void)HFQDataRequest_Mao:(RequestMethod)method URLString:(nonnull NSString*)URLString parameters:(nullable NSDictionary<NSString*, id>*)parameters success:(nonnull void (^)(_Nullable id responseObject))success failure:(nonnull void(^)(_Nullable id responseObject,  NSError * _Nullable error))failure {
    
    NSMutableString *body = [[NSMutableString alloc]init];;
    for(NSString *key in [parameters allKeys]){
        NSString *value= [parameters objectForKey:key];
        [body appendString:[NSString stringWithFormat:@"%@=%@&",key,value]];
    }
    NSLog(@"\n\n\n[-------Send------]:%@?%@\n\n\n",URLString,body);
    
    NSError *exError;
    NSMutableURLRequest *request = [self HTTPRequestWithMethod:method URLString:URLString parameters:parameters error:&exError];
    if(exError) {
        failure(nil, exError);
        return;
    }
    request.timeoutInterval = 30.f;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"accept"];
    [request setHTTPShouldHandleCookies:NO];
    if ([AD_UserDefaults objectForKey:ASJFMyUserLoginTokenKey]) {
        [request setValue:[AD_UserDefaults objectForKey:ASJFMyUserLoginTokenKey]  forHTTPHeaderField:@"token"];
    }
    [request setValue:@"ASJF" forHTTPHeaderField:@"APP-TYPE"];
    NSMutableDictionary *tempMutDic = [NSMutableDictionary dictionaryWithDictionary:parameters];
    if (method == RequestMethodGet) {
        
    }else {
        NSData *str = [NSJSONSerialization dataWithJSONObject:tempMutDic options:NSJSONWritingPrettyPrinted error:nil];
        [request setHTTPBody: str];
    }
   
    
    [self dataWithRequest:request responseConfig:^id<AFURLResponseSerialization> _Nullable{
        
        AFHTTPResponseSerializer *serializer;
        if(parameters && [parameters.allKeys containsObject:@"service"]) {
            serializer = [AFHTTPResponseSerializer serializer];
        } else {
            serializer = [AFHTTPResponseSerializer serializer];
            [serializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/xml",@"text/plain", @"application/xml", nil]];
        }
        
        return serializer;
        
    } completionHandler:^(NSURLResponse * _Nullable response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        NSLog(@"%@",[responseObject mj_JSONString]);
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        NSString *jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSData *resData = [[NSData alloc]initWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
        NSMutableDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        
        if (error) {
            NSLog(@"\n\n\n[---失败Result----%li--]:%@     --request.URL-->%@\n\n\n",(long)httpResponse.statusCode,error,httpResponse.URL);
            
            [HUD_Mao showCharacterMessage:error.localizedDescription];
            failure(response,error);
        }else {
            NSLog(@"\n\n\n[---成功Result----%li--]:%@     --request.URL-->%@\n\n\n",(long)httpResponse.statusCode,resultDic,httpResponse.URL);
            
            if ([[NSString stringWithFormat:@"%@",[resultDic objectForKey:@"code"]] isEqualToString:@"401"]) {
                UIViewController *vc = [[Mediator sharedInstance] login_mainViewController];
                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:vc animated:YES completion:nil];
                success(resultDic);
            }else if ([[NSString stringWithFormat:@"%@",[resultDic objectForKey:@"code"]] isEqualToString:@"200"]) {
                
                success(resultDic);
            }else {
                [HUD_Mao showCharacterMessage:[NSString stringWithFormat:@"%@",[resultDic objectForKey:@"message"]]];
                success(resultDic);
            }
        }
    }];
}
/**
 通用数据请求
 
 @param method 请求方式
 @param URLString 请求地址
 @param parameters 参数
 @param success 成功回调
 @param failure 失败回调
 */
-(void)HFQDataCommonRequest_Mao:(RequestMethod)method URLString:(nonnull NSString*)URLString parameters:(nullable NSDictionary<NSString*, id>*)parameters success:(nonnull void (^)(_Nullable id responseObject))success failure:(nonnull void(^)(_Nullable id responseObject,  NSError * _Nullable error))failure {
    
    NSMutableString *body = [[NSMutableString alloc]init];;
    for(NSString *key in [parameters allKeys]){
        NSString *value= [parameters objectForKey:key];
        [body appendString:[NSString stringWithFormat:@"%@=%@&",key,value]];
    }
    NSLog(@"\n\n\n[-------Send------]:%@?%@\n\n\n",URLString,body);
    
    NSError *exError;
    NSMutableURLRequest *request = [self HTTPRequestWithMethod:method URLString:URLString parameters:parameters error:&exError];
    if(exError) {
        failure(nil, exError);
        return;
    }
    request.timeoutInterval = 30.f;
    
    [self dataWithRequest:request responseConfig:^id<AFURLResponseSerialization> _Nullable{
        
        AFHTTPResponseSerializer *serializer;
        if(parameters && [parameters.allKeys containsObject:@"service"]) {
            serializer = [AFHTTPResponseSerializer serializer];
        } else {
            serializer = [AFJSONResponseSerializer serializer];
            [serializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"text/plain", nil]];
        }
        
        return serializer;
        
    } completionHandler:^(NSURLResponse * _Nullable response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        
        NSLog(@"\n\n\n[---Result----%li--]:%@     --request.URL-->%@\n\n\n",(long)httpResponse.statusCode,responseObject,httpResponse.URL);
        
        if (error) {
            failure(response,error);
        }else {
            success(responseObject);
        }
        
    }];
}

/**
 上传
 
 @param method 请求方式
 @param URLString 请求地址
 @param parameters 参数
 @param file 文件
 @param success 成功回调
 @param failure 失败回调
 */
-(void)HFQUploadRequest_Mao:(RequestMethod)method URLString:(NSString*)URLString parameters:(NSDictionary<NSString*, id>*)parameters file:(HFQFileObject*)file success:(void (^)(id responseObject))success failure:(void(^)(id responseObject, NSError *error))failure {
    
    [self HFQUploadRequest_Mao:method URLString:URLString parameters:parameters files:@[file] progress:nil success:success failure:failure];
    
}

/**
 上传（带进度）
 
 @param method 请求方式
 @param URLString 请求地址
 @param parameters 参数
 @param file 文件
 @param progress 进度
 @param success 成功回调
 @param failure 失败回调
 */
-(void)HFQUploadRequest_Mao:(RequestMethod)method URLString:(NSString*)URLString parameters:(NSDictionary<NSString*, id>*)parameters file:(HFQFileObject*)file progress:(void (^)(int64_t totalUnitCount, int64_t completedUnitCount))progress success:(void (^)(id responseObject))success failure:(void(^)(id responseObject, NSError *error))failure {
    
    [self HFQUploadRequest_Mao:method URLString:URLString parameters:parameters files:@[file] progress:progress success:success failure:failure];
    
}


/**
 多文件上传 （由于服务端限制，此方法暂时不建议使用）
 
 @param method 请求方式
 @param URLString 请求地址
 @param parameters 参数
 @param files 文件集合
 @param progress 进度
 @param success 成功回调
 @param failure 失败回调
 */
-(void)HFQUploadRequest_Mao:(RequestMethod)method URLString:(NSString*)URLString parameters:(NSDictionary<NSString*, id>*)parameters files:(NSArray<HFQFileObject*>*)files progress:(void (^)(int64_t totalUnitCount, int64_t completedUnitCount))progress success:(void (^)(id responseObject))success failure:(void(^)(id responseObject, NSError *error))failure {
    if(!files || files.count == 0) {
        NSString *localizedDescription = @"参数：<files> 不允许为空";
        NSDictionary *errorInfo = @{NSLocalizedDescriptionKey: localizedDescription, NSLocalizedFailureReasonErrorKey: localizedDescription};
        failure(nil, [NSError errorWithDomain:HFQErrorDomain code:-299 userInfo:errorInfo]);
        return;
    }
    NSError *exError;
    NSMutableURLRequest *request = [self multipartFormRequestWithMethod:method URLString:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (HFQFileObject *file in files) {
            [formData appendPartWithFileData:file.data name:file.name fileName:file.fileName mimeType:file.mimeType];
        }
    } error:&exError];
    if(exError) {
        failure(nil, exError);
        return;
    }
    [request setValue:@"application/json" forHTTPHeaderField:@"accept"];
    [self uploadWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
        if(progress) {
            NSLog(@"进度展示：%f",1.0f*uploadProgress.completedUnitCount/uploadProgress.totalUnitCount);
            progress(uploadProgress.totalUnitCount, uploadProgress.completedUnitCount);
        }
    } completionHandler:^(NSURLResponse * _Nullable response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        NSString *jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSData *resData = [[NSData alloc]initWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
        NSMutableDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",resultDic);
        if (responseObject) {
            NSLog(@"\n\n\n[---上传打印----%li--]:%@     --request.URL-->%@\n\n\n",(long)httpResponse.statusCode,[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error],httpResponse.URL);
        }else {
            NSLog(@"\n\n\n[---上传打印----%li--]:%@     --request.URL-->%@\n\n\n",(long)httpResponse.statusCode,@"nil",httpResponse.URL);
        }
        if(error) {
            failure(responseObject, error);
        } else {
            success(resultDic);
        }
    }];
}


@end
